package com.fate.system.service.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.fate.framework.utils.CommonUtil;
import com.fate.framework.utils.HttpUtil;
import com.fate.system.dto.wx.AccessTokenDTO;
import com.fate.system.service.IWxService;
import com.fate.system.vo.wx.WxOpenIdVO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
@Service
public class WxServiceImpl implements IWxService {
  @Value("${wx.appId}")
  private String appId;

  @Value("${wx.appSecret}")
  private String appSecret;

  @Override
  public AccessTokenDTO getAccessToken() throws Exception {
    String res =
        HttpUtil.sendGet(
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId
                + "&secret="
                + appSecret);

    return JSON.parseObject(res, AccessTokenDTO.class);
  }

  @Override
  public void getQrCode(
      String path,
      String envVersion,
      Integer width,
      Boolean isHyaline,
      HttpServletResponse response)
      throws Exception {
    if (CommonUtil.isNullOrEmpty(envVersion)) {
      envVersion = "release";
    }
    if (CommonUtil.isNullOrEmpty(width)) {
      width = 430;
    }

    if (CommonUtil.isNullOrEmpty(isHyaline)) {
      isHyaline = false;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
      // 创建请求对象
      HttpPost httpPost = getHttpPost(width, isHyaline, path, envVersion);

      // 执行请求
      CloseableHttpResponse innerResponse = httpClient.execute(httpPost);
      HttpEntity responseEntity = innerResponse.getEntity();

      if (responseEntity != null) {
        // 检查返回内容类型
        String contentType = responseEntity.getContentType().getValue();
        if (contentType.contains("application/json")) {
          // 返回的是错误信息
          String responseStr = EntityUtils.toString(responseEntity, "UTF-8");
          System.out.println("Error Response: " + responseStr);
          response.setContentType("application/json");
          response.getWriter().write(responseStr);
        } else {
          // 返回的是图片Buffer
          response.setContentType("image/png");
          try (InputStream inputStream = responseEntity.getContent();
              OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
              outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
          }
        }
      }

      innerResponse.close();
    } catch (IOException e) {
      log.error("获取小程序二维码异常", e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.getWriter().write("获取小程序二维码异常");
    } finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        log.error("关闭HttpClient异常", e);
      }
    }
  }

  @Override
  public WxOpenIdVO getUserOpenId(String code) throws Exception {
    String wxLoginUrl =
        "https://api.weixin.qq.com/sns/jscode2session"
            + "?appid="
            + appId
            + "&secret="
            + appSecret
            + "&js_code="
            + code
            + "&grant_type=authorization_code";

    String res = HttpUtil.sendGet(wxLoginUrl);
    return JSON.parseObject(res, WxOpenIdVO.class);
  }

  public HttpPost getHttpPost(Integer width, Boolean isHyaline, String path, String envVersion)
      throws Exception {
    HttpPost httpPost =
        new HttpPost(
            "https://api.weixin.qq.com/wxa/getwxacode?access_token="
                + getAccessToken().getAccess_token());

    // 设置请求头
    httpPost.setHeader("Content-Type", "application/json");

    // 构建请求参数
    JSONObject jsonParams = new JSONObject();
    jsonParams.accumulate("path", path);
    jsonParams.accumulate("width", width);
    jsonParams.accumulate("env_version", envVersion);
    jsonParams.accumulate("is_hyaline", isHyaline);

    // 设置请求参数
    StringEntity entity = new StringEntity(jsonParams.toString(), "UTF-8");
    httpPost.setEntity(entity);
    return httpPost;
  }
}
